import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  ToolingListDto,
  ToolingServiceProxy,
  StockOperationLogListDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';

import { Table } from 'primeng/table';

@Component({
  selector: 'toolingLogModal',
  templateUrl: './tooling-log-modal.component.html'
})
export class ToolingLogModalComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('logDataTable') logDataTable: Table;
  @ViewChild('logPaginator') logPaginator: Paginator;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;

  tooling = new ToolingListDto();

  operationNames = ['借出/配备', '返修', '送检', '技改', '隔离', '报废'];

  advancedFiltersAreShown = false;
  filterText = '';
  tab = 0;

  logs = new Array<StockOperationLogListDto>();

  constructor(
    injector: Injector,
    private _toolingService: ToolingServiceProxy
  ) {
    super(injector);
  }

  show(tooling: ToolingListDto): void {
    this.tooling = tooling;

    this.active = true;

    this.modal.show();

    this.tab = 1;

    this.getToolingLogs();
  }

  getToolingLogs(event?: LazyLoadEvent) {
    if (!this.tooling || !this.tooling.id) {
      return;
    }

    if (this.tab === 0) {
      return;
    }

    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.logPaginator.changePage(0);
      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._toolingService
      .getToolingLogs(
        this.tooling.id,
        this.filterText,
        undefined,
        this.primengTableHelper.getSorting(this.logDataTable),
        this.primengTableHelper.getMaxResultCount(this.logPaginator, event),
        this.primengTableHelper.getSkipCount(this.logPaginator, event)
      )
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  reloadPage(): void {
    this.logPaginator.changePage(this.logPaginator.getPage());
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }

  tabChange(tab: number) {
    this.tab = tab;
    this.reloadPage();
  }
}
